package org.common.entity;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.common.constant.Code;
import org.common.constant.Message;

import java.io.Serializable;
import java.util.Objects;

/**
 * 统一的请求返回结果
 *
 * @author LiKun
 * @date 2021/11/8 18:44
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ApiModel("返回结果实体类")
public class Result<T> implements Serializable {

    @ApiModelProperty(name = "code", notes = "返回数据")
    private T data;

    @ApiModelProperty(name = "code", notes = "返回提示码")
    private int code;

    @ApiModelProperty(name = "code", notes = "返回提示信息")
    private String message;


    /*-----------------------------------------------constructor methods----------------------------------------------*/


    public Result(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public Result(int code, String message, T data) {
        this.data = data;
        this.code = code;
        this.message = message;
    }


    /*----------------------------------------------public static methods---------------------------------------------*/


    public static Result<String> success() {
        return new Result<>(Code.SUC, Message.SUC);
    }

    public static <T> Result<T> success(T data) {
        return new Result<>(Code.SUC, Message.SUC, data);
    }

    public static Result<String> fail() {
        return new Result<>(Code.FAIL, Message.FAIL);
    }

    public static <T> Result<T> fail(T data) {
        return new Result<>(Code.FAIL, Message.FAIL, data);
    }

    public static <T> Result<T> fail(String message, T data) {
        return new Result<>(Code.FAIL, message, data);
    }

    /**
     * 判断给定的 {@link Result} 的状态是否为成功
     *
     * @param result 待判断对象
     *
     * @return 状态是否为 {@link Code#SUC}
     */
    public static boolean isSuccess(Result result) {
        return Objects.nonNull(result) && result.code == Code.SUC;
    }

}
